package com.etop.jansing.dao;

import com.etop.jansing.entities.ResourcePermission;
import com.etop.jansing.entities.Role;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;

/**
 * Created by jansing on 2015/10/25.
 */
@Repository
public class RoleDao extends BaseDao<Role> {

    public Role getByNameIgnoreValid(String name) {
        return (Role) getSession().createQuery("from Role r where r.name=:name")
                .setString("name", name)
                .uniqueResult();
    }

    public Role getByName(String name) {
        return (Role) getSession().createQuery("from Role r where r.name=:name and r.valid=true")
                .setString("name", name)
                .uniqueResult();
    }

    /**
     * 如果严格遵守要求，可以直接用user.getRoleList()得到其角色list，<br/>
     * 严格要求指：在用户管理中取消某个用户的某个角色时，执行下面的代码：<br/>
     * user.getRoleList.remove(deleteRole);
     * roleService.delete(deleteRole);
     *
     * @param uid
     * @return
     */
    public List<Role> getByUser(long uid) {
        Session session = getSession();
        return session.createQuery("select r from User u left join u.roleList r" +
                " where u.id=:uid" +
                " and r.valid=true")
                .setLong("uid", uid)
                .list();
    }

    public List<Role> getByIds(Collection<Long> rids) {
        Session session = getSession();
        return session.createQuery("from Role r where r.id in (:rids) and r.valid=true")
                .setParameterList("rids", rids)
                .list();
    }

    public List<Role> list() {
        Session session = getSession();
        return session.createQuery("from Role r where r.valid=true").list();
    }

    /**
     * 该角色被使用的情况
     *
     * @param id
     * @return
     */
    public int isUsing(long id) {
        Session session = getSession();
        return session.createQuery("from User u left join  u.roleList r where r.id=:id and u.valid=true")
                .setLong("id", id)
                .list()
                .size();
    }
}
